use std::fs;

use csv::Reader;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;

use crate::cli::OutputFormat;

#[derive(Debug, Deserialize, Serialize)]
pub struct Palyer {
    #[serde(rename = "Name")]
    pub name: String,
    #[serde(rename = "Position")]
    pub posittion: String,
    #[serde(rename = "DOB")]
    pub dob: String,
    #[serde(rename = "Nationality")]
    pub nationnality: String,
    #[serde(rename = "Kit Number")]
    pub kit: u8,
}

pub fn process_csv(input: &str, output: String, format: OutputFormat) -> anyhow::Result<()> {
    let mut read = Reader::from_path(input)?;
    let headers = read.headers()?.clone();
    let mut ret = Vec::with_capacity(128);
    for result in read.records() {
        let record = result?;
        // headers.iter() ->使用 headers 的迭代器
        //  record.iter() -> 使用 record的迭代器
        // zip()-> 将两个迭代器合并成一个元组迭代器[(header,record),..]
        // collect::<Value>->  将元组迭代器转换成 JSON Value
        let json_value = headers.iter().zip(record.iter()).collect::<Value>();
        ret.push(json_value);
    }
    let content: String = match format {
        OutputFormat::Json => serde_json::to_string_pretty(&ret)?,
        OutputFormat::Yaml => serde_yaml::to_string(&ret)?,
    };

    Ok(fs::write(output, content)?)
}
